//
//  XTHomeTableVC.swift
//  Weibo(Swift)
//
//  Created by 肖霆 on 16/5/10.
//  Copyright © 2016年 肖霆. All rights reserved.
//

import UIKit

private let HomeTableViewCellID = "HomeTableViewCellID"

class XTHomeTableVC: XTVisitorTabVC {
    
    //加载微博数据数组
    private lazy var statusListViewModel : XTStatusListViewModel = XTStatusListViewModel()
    
    //懒加载提示刷新多少条的label
    private lazy var tipLabel:UILabel = {
        
        let label = UILabel(textColor: UIColor.whiteColor(), fronSize: 12)
        label.backgroundColor = UIColor.orangeColor()
        label.textAlignment = .Center
        label.hidden = true
        return label
        
    }()
    
    //懒加载上拉刷新动画
    private lazy var pullUpView :UIActivityIndicatorView = {
    
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        view.color = UIColor.blueColor()
        return view
    
    }()
    //懒加载自定义下拉刷新视图
    private lazy var myPullDownView:XTRefreshControl = {
    let view = XTRefreshControl()
        return view
    
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if userLogin{
            //设置tableView的相关操作
            setupTableView()
            //加载数据
            loadStatus()
            //设置UI
            setupUI()
            
        
        
        
        }else {
            //未登陆状态下
            visitorView?.setVisitorInfo(nil, imgName: nil)
        }
    }
    //加载数据的函数
    private func loadStatus(){
       
        
        statusListViewModel.requestStatus(pullUpView.isAnimating()) { (isSuccess, message) -> () in
            
            
            if !self.pullUpView.isAnimating(){
                //将请求返回的message传给tiplabel
                self.startTipAnimation(message)
                
            }
        
            if isSuccess{
                self.tableView.reloadData()
            }
        
            self.endRefresh()//该停止必须放在最后，要不然会让self.pullUpView.isAnimating的判断为停止，然后就通过判断执行了tiplabel的动画
        }
    
    }
    
    func endRefresh(){
        //让下拉刷新的等待菊花停止
        pullUpView.stopAnimating()
        //让自定义下拉刷新回到默认隐藏状态
        myPullDownView.endRefresh()
    }
    
    private func setupUI(){
        if let nav = self.navigationController{
            tipLabel.frame = CGRectMake(0, CGRectGetMaxY(nav.navigationBar.frame) - 35 , tableView.frame.size.width, 35)
        nav.view.insertSubview(tipLabel, belowSubview: nav.navigationBar)
        }
    
    
    }
    private func setupTableView(){
        //注册一个cell，相当于xib中给一个cell ID
        tableView.registerClass(XTHomeTableViewCell.self, forCellReuseIdentifier: HomeTableViewCellID)
        
        //自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        //设置预估行高
        tableView.estimatedRowHeight = 200
        
        //去掉分割线
        tableView.separatorStyle = .None
        //在footview添加加载指示器
        tableView.tableFooterView = pullUpView
        pullUpView.sizeToFit()
        
        myPullDownView.addTarget(self, action: "pullDownRefresh", forControlEvents: .ValueChanged)
        tableView.addSubview(myPullDownView)
    
    }
    
    //myPullDownView监听实现方法
    @objc private func pullDownRefresh(){
    
        loadStatus()
    }
    //tipLabel的动画
    private func startTipAnimation(message:String){
        //防止动画多次之行
        if tipLabel.hidden == false{
        return
        }
        tipLabel.text = message
        tipLabel.hidden = false
        
//        添加延时执行动画
//       UIView.animateKeyframesWithDuration(<#T##duration: NSTimeInterval##NSTimeInterval#>, delay: <#T##NSTimeInterval#>, options: <#T##UIViewKeyframeAnimationOptions#>, animations: <#T##() -> Void#>, completion: <#T##((Bool) -> Void)?##((Bool) -> Void)?##(Bool) -> Void#>)
        UIView.animateWithDuration(1, animations: { () -> Void in
             self.tipLabel.transform = CGAffineTransformMakeTranslation(0, self.tipLabel.frame.height)
            }) { (_) -> Void in
//                伸出来之后再缩回去
                UIView.animateWithDuration(1, animations: { () -> Void in
                    self.tipLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        self.tipLabel.hidden = true
                })
               
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListViewModel.statusList?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeTableViewCellID, forIndexPath: indexPath) as! XTHomeTableViewCell
        
        
        //给cell的数据模型传数据
        cell.statusViewModel = statusListViewModel.statusList![indexPath.row]
        //去掉选中状态
        cell.selectionStyle = .None
        
        
        return cell
        
    }

    
    //cell将要显示时调用的方法
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        print(indexPath.row)
        
        if indexPath.row == statusListViewModel.statusList!.count - 1 && !pullUpView.isAnimating(){
        print("我时最后一个cell")
            pullUpView.startAnimating()
            //请求数据
            loadStatus()
        }
    }
}
